const db = require('../conn.js');
const r = require('../err.js');

module.exports = (app)=>{
	app.route('/node/login')
	.get((req, res)=>{
		let query = req.query;
		let app = req.qpp;
		if (!query.name || !query.password) {
			res.json(r.error(1));
			return;
		}

		let users = db.get('users');
		let tokens = db.get('tokens');
		(async function(){
			try{
				let user = await users.findOne({
					name: req.query.name,
					password: req.query.password
				});
				var token = query.name + '@' + new Date().getTime();
				token = new Buffer(token).toString('base64');
				await tokens.update({name:req.query.name},{$set:{token}},{upsert:true});
				if (user != null) {
					res.json(r.success({token}));
				}else{
					res.json(r.error(2));
				}
			}catch(e){
				console.log(e);
				res.json(makeRes(500,e.toString(),''));
			}
		})();
	});
}
